package com.echo.im.client.handler.message.suport;


import com.echo.im.client.handler.message.AbstractMessageHandler;
import com.echo.im.client.helper.OnlineStatusHelper;
import com.echo.im.common.enums.IMCmdType;
import com.echo.im.common.enums.IMTerminalType;
import com.echo.im.common.model.IMRecvInfo;
import com.echo.im.common.model.IMUserInfo;
import com.echo.im.common.model.message.IMGroupMessage;
import com.echo.im.common.vo.message.GroupMessageVO;
import com.echo.im.mq.event.producer.EventPublisher;
import com.echo.im.mq.event.model.GroupPushMessageEvent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: echo
 * @time: 2024-08-14
 */
@Component
public class GroupMessageHandler extends AbstractMessageHandler<IMGroupMessage, GroupMessageVO> {

    private final String appName;
    private final EventPublisher eventPublisher;
    private final GroupPushMessageEvent groupPushMessageEvent;

    public GroupMessageHandler(OnlineStatusHelper onlineStatusHelper, @Value("${spring.application.name}")String appName, EventPublisher eventPublisher, GroupPushMessageEvent groupPushMessageEvent) {
        super(onlineStatusHelper, appName);
        this.appName = appName;
        this.eventPublisher = eventPublisher;
        this.groupPushMessageEvent = groupPushMessageEvent;
    }

    @Override
    public void handleMessage(IMGroupMessage message) {
        // 根据群聊每个成员所连的IM-server，进行分组
        Map<Integer, List<IMUserInfo>> serverIdUserInfoMap = onlineStatusHelper.getServerIdUserInfoMap(message.getRecvIds());

        // 逐个server发送
        for (Map.Entry<Integer, List<IMUserInfo>> entry : serverIdUserInfoMap.entrySet()) {
            IMRecvInfo<GroupMessageVO> recvInfo = new IMRecvInfo<>();
            recvInfo.setCmd(IMCmdType.GROUP_MESSAGE.code());
            recvInfo.setReceivers(new LinkedList<>(entry.getValue()));
            recvInfo.setSender(message.getSender());
            recvInfo.setServiceName(appName);
            recvInfo.setSendResult(message.getSendResult());
            recvInfo.setData(message.getData());
            // 推送至队列

            eventPublisher.publish(groupPushMessageEvent.topic(), groupPushMessageEvent.buildEventMessage(recvInfo));
        }

        // 推送给自己的其他终端
        if (message.getSendToSelf()) {
            List<Integer> recvTerminals= IMTerminalType.codes().stream().filter(terminal -> !terminal.equals(message.getSender().getTerminal())).collect(Collectors.toList());
            Map<Integer, List<Integer>> serverIdMap = onlineStatusHelper.getServerIdTerminalListMap(message.getSender().getId(), recvTerminals);
            serverIdMap.forEach((serverId, terminals)->{
                // 获取终端连接的channelId
                IMRecvInfo<GroupMessageVO> recvInfo = this.createRecvInfoForSelf(message, terminals);
                // 如果终端在线，将数据推送到消息队列，等待拉取推送
                eventPublisher.publishWithServerId(groupPushMessageEvent.topic(),serverId.toString(), groupPushMessageEvent.buildEventMessage(recvInfo));
            });
        }

        // 对于离线用户 群聊消息不负责推送，由用户自己拉取
    }
}
